package com.example.myproject.client;

import java.util.ArrayList;

import com.google.gwt.json.client.JSONParser;
import com.google.gwt.storage.client.Storage;
import com.google.gwt.json.client.*;

public class Save {

	private static Storage saveInfo = Storage.getLocalStorageIfSupported();
	
	public static void clearStorage() {
		saveInfo.clear();
	}
	
	// convert moduleArray into strings
	public static void array2save(ArrayList<Module> modArray) {
		String string;
		int i = 0;
		for (Module mod : modArray) {
			string = mod.toSaveString();
			saveInfo.setItem("module" + i, string);
			i++;
		}	
	}
	
	// convert string to moduleArray
	public static ArrayList<Module> getArrayFromStorage() {
		ArrayList<Module> temp = new ArrayList<Module>();
		
		JSONNumber jN;
		JSONString jS;
		int code;
		String status;
		int orient;
		int x;
		int y;
		
		for (int i =  0; i < saveInfo.getLength(); i++) {
			String modString = saveInfo.getItem("module" + i);
			JSONObject jO = (JSONObject)JSONParser.parseLenient(modString);
			jN = (JSONNumber) jO.get("code");
			code = (int)jN.doubleValue();
			jS = (JSONString) jO.get("status");
			status = jS.stringValue();
			jN = (JSONNumber) jO.get("turns");
			orient = (int)jN.doubleValue();
			jN = (JSONNumber) jO.get("X");
			x = (int)jN.doubleValue();
			jN = (JSONNumber) jO.get("Y");
			y = (int)jN.doubleValue();
			Module mod = new Module(code, status, orient, x, y);
			temp.add(mod);
		}				
	return temp;
	}

}